package com.fourhats.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fourhats.dao.ProductBuyedDAO;
import com.fourhats.model.ProductBuyed;

@Repository
public class ProductBuyedDAOImpl extends GenericDAOImpl<ProductBuyed, Long> implements ProductBuyedDAO {

	protected ProductBuyedDAOImpl() {
		super(ProductBuyed.class.getName());
	}

	@SuppressWarnings("unchecked")
	public List<ProductBuyed> getPurchasedProducts(long userId) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.add(Restrictions.eq("user.id", userId));
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<ProductBuyed> getSoldProducts(long userId) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		
		criteria.createAlias("product.market", "productMarket");
		criteria.createAlias("productMarket.user", "productMarketUser");
		
		criteria.add(Restrictions.eq("productMarketUser.id", userId));
		
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<ProductBuyed> getSoldProductsSince(long userId, Date date) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		
		criteria.createAlias("product.market", "productMarket");
		criteria.createAlias("productMarket.user", "productMarketUser");
		
		criteria.add(Restrictions.eq("productMarketUser.id", userId));
		criteria.add(Restrictions.gt("buyDate", date));
		
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return getHibernateTemplate().findByCriteria(criteria);
	}
}
